#include "timer.h"
#include <time.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>

// 获取当前时间(系统启动的时间到现在的时间)
static uint32_t now()
{
    struct timespec spec;
    clock_gettime(CLOCK_MONOTONIC, &spec);
    uint32_t now = spec.tv_sec * 1000;
    now += spec.tv_nsec / 1000000;
    return now;
}

min_heap_t* min_heap;

// 初始化定时器
void init_timer()
{
    min_heap = (min_heap_t*)malloc(sizeof(min_heap_t));
    min_heap_ctor_(min_heap);
}

// 添加定时器
timer_entry_t* add_timer(uint32_t msec, timer_handler_pt calllback, bool always)
{
    timer_entry_t* te = (timer_entry_t*)malloc(sizeof(*te));
    if (!te)
    {
        return NULL;
    }
    memset(te, 0, sizeof(*te));

    te->handler = calllback;
    te->expired = now() + msec;
    te->always = always;
    te->gap = msec;

    if (0 != min_heap_push_(min_heap, te))
    {
        free(te);
        return NULL;
    }
    return te;
}

// 删除定时器
bool del_timer(timer_entry_t* e)
{
    return 0 == min_heap_erase_(min_heap, e);
}

// 检测定时器
void check_timer()
{
    uint32_t cur = now();
    while (true)
    {
        timer_entry_t* te = min_heap_top_(min_heap);
        if (!te) break;                 // 空堆
        if (te->expired > cur) break;      // 没有过期的
        
        // 执行定时回调
        te->handler(te);
        min_heap_pop_(min_heap);

        if (!te->always)    // 不是一直循环执行的,释放
        {
            printf("free\n");
            free(te);
        }
        else  
        {
            printf("continue\n");
            te->expired = cur + te->gap;
            min_heap_push_(min_heap, te);
        }
    }
}

// 最近触发的定时任务离当前的时间
int time_to_sleep()
{
    timer_entry_t* te = min_heap_top_(min_heap);
    if (!te)
    {
        return 0;
    }
    int diss = te->expired - now();
    return diss > 0 ? diss : 0;
}

// 释放定时器
void des_timer()
{
    min_heap_dtor_(min_heap);
}